// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
    var o   = parseUri.options,
	m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
	uri = {},
	i   = 14;
	
	while (i--) uri[o.key[i]] = m[i] || "";
	
	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	    });
	
	return uri;
};

parseUri.options = {
    strictMode: false,
    key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
    q:   {
	name:   "queryKey",
	parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
	strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
	loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
    }
};

// Note: this must match LibraryManager::clean_label()
function clean_label(label) {
    var clean = label.toLowerCase();
    clean = clean.replace(new RegExp(/[ \/]/g), '-');
    clean = clean.replace(new RegExp(/[)(]/g), '');
    return clean;
}

function param_or_null (uri, name) {
    if (!uri.queryKey.hasOwnProperty(name)) return null;
    return uri.queryKey[name];
}

function AccessLibrary() {
    var prefs = new gadgets.Prefs();
    var audience = prefs.getString("audience");
    if (audience == "") { audience = null; }
    var page_uri = parseUri(gadgets.util.getUrlParameters()["parent"]);
    var library_base = page_uri.protocol + "://" + page_uri.host + page_uri.path;
    var mode = param_or_null(page_uri, 'mode');
    var labels = new Array();
    var query = param_or_null(page_uri, 'q');
    if (query != null) {
	labels = query.split(' ');
    }
    var id = param_or_null(page_uri, 'id');
    switch (mode) {
    case "document":
	RequestDocumentMetadata(id);
	break;
    case "slice":
	RequestSliceDocuments(library_base, audience, labels);
	break;
    case "index":
    default:
	RequestIndexDocuments(library_base, audience);
	break;
    }
}

function RequestIndexDocuments(library_base, audience) {
    var url = "http://global-learning-portal-2.appspot.com/admin/library/documents";
    if (audience) { url += "?q=audience:" + audience; }
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 0;
    var callback = function(obj) {
	DocumentListCallback(library_base, obj.data);
    };
    gadgets.io.makeRequest(url, callback, params);
}

function RequestSliceDocuments(library_base, audience, labels) {
    var query_labels = labels.slice();
    if (audience) { query_labels.push("audience:" + audience); }
    var url = "http://global-learning-portal-2.appspot.com/admin/library/documents";
    if (query_labels.length != 0) { url += "?q=" + query_labels.join('+'); }
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 0;
    var callback = function(obj) {
	DocumentListCallback(library_base, obj.data);
    };
    gadgets.io.makeRequest(url, callback, params);
}

function DocumentSorter(a, b) {
    return a.title.toLocaleLowerCase().localeCompare(b.title.toLocaleLowerCase());
}

function DocumentListCallback(library_base, documents) {
    var html = "<table>";
    for (var i in documents.sort(DocumentSorter)) {
	var doc = documents[i];
	var info_url = library_base + "?mode=document&id=" + doc.id;
	var ext = '';
	var description = doc.description;
	if (description.length > 150) {
	    description = description.substr(0, 140) + "... <a href=\"" + info_url + "\" target=\"_top\">(read more)</a>";
	}
	// TODO(sdd): css instead of tables
	html += "<tr><td class=\"glp_library_index_title\"><a href=\"" + info_url + 
	    "\" target=\"_top\">" + doc.title + "</a></td></tr><tr><td class=\"glp_library_index_description\">" +
	    description + "</td></tr>"
    }
    if (documents.length == 0) {
	html = "<tr><td colspan=\"2\"><em>No documents found for this topic.</em></td></tr>"
	    }
    html += "</table>"
    document.getElementById('view').innerHTML = html;
    gadgets.window.adjustHeight();
}

function RequestDocumentMetadata(id) {
    if (id == null) {
	RequestDocumentMetadataCallback(null);
    } else {
	var url = "http://global-learning-portal-2.appspot.com/admin/library/documents?id=" + id;
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 0;
	var callback = function(obj) {
	    RequestDocumentMetadataCallback(obj.data);
	};
	gadgets.io.makeRequest(url, callback, params);
    }
}

function RequestDocumentMetadataCallback(doc) {
    var html = '<b><em>Invalid document ID.</b></em>';
    if (doc != null) {
	var authors = doc.authors.join('; ');
	var sources = doc.sources.join('; ');
	var labels = doc.labels.sort(LabelSorter);
	var document_type = ExtractLabelSet(labels, 'type');
	var document_topics = ExtractLabelSet(labels, 'topic');
	var document_grades = ExtractLabelSet(labels, 'grade');
	var document_audiences = ExtractLabelSet(labels, 'audience');
	var document_origins = ExtractLabelSet(labels, 'origin');
	// TODO(sdd): css instead of tables
	html = "<table><tr><td class=\"glp_library_document_field\">Title:</td>" + 
	    "<td class=\"glp_library_document_value\"><a href=\"" + doc.url
	    + "\" target=\"_blank\">" + doc.title + "</a></td></tr>" + 
	    "<tr><td class=\"glp_library_document_field\">Author:</td>" +
	    "<td class=\"glp_library_document_value\">" + authors +
	    "</td></tr><tr><td class=\"glp_library_document_field\">Description:</td>" + 
	    "<td class=\"glp_library_document_value\">" + doc.description +
	    "</td></tr><tr><td class=\"glp_library_document_field\">Type:</td>" +
	    "<td class=\"glp_library_document_value\">" + document_type +
	    "</td></tr><tr><td class=\"glp_library_document_field\">Topics:</td>" +
	    "<td class=\"glp_library_document_value\">" + document_topics +
	    "</td></tr><tr><td class=\"glp_library_document_field\">Grade Level(s):</td>" +
	    "<td class=\"glp_library_document_value\">" + document_grades +
	    "</td></tr><tr><td class=\"glp_library_document_field\">Audience(s):</td>" +
	    "<td class=\"glp_library_document_value\">" + document_audiences +
	    "</td></tr><tr><td class=\"glp_library_document_field\">Origin(s):</td>" +
	    "<td class=\"glp_library_document_value\">" + document_origins +
	    "</td></tr></table>";
    }
    document.getElementById('view').innerHTML = html;
    gadgets.window.adjustHeight();
}

function LabelSorter(a, b) {
    return a[1].toLocaleLowerCase().localeCompare(b[1].toLocaleLowerCase());
}

function ExtractLabelSet(labels, set_name) {
    var prettified = []
    for (var label in labels) {
	if (labels[label][0].substr(0, set_name.length + 1) == set_name + ":") {
	    prettified.push(labels[label][1]);
	}
    }
    if (prettified.length == 0) { return "<em>n/a</em>"; }
    return prettified.join(', ');
}

gadgets.util.registerOnLoadHandler(AccessLibrary)
